package com.xh.bussiness.exam.service.impl;

import com.xh.bussiness.exam.bean.dto.ExerciseDto;
import com.xh.bussiness.exam.bean.dto.StudentExerciseDto;
import com.xh.bussiness.exam.bean.request.ExerciseRequest;
import com.xh.bussiness.exam.bean.request.StudentExerciseRequest;
import com.xh.bussiness.exam.model.Exercise;
import com.xh.bussiness.exam.model.ExerciseStudentQuestion;
import com.xh.bussiness.exam.model.StudentExercise;
import com.xh.bussiness.exam.dao.StudentExerciseMapper;
import com.xh.bussiness.exam.service.IExerciseService;
import com.xh.bussiness.exam.service.IExerciseStudentQuestionService;
import com.xh.bussiness.exam.service.IStudentExerciseService;
import com.xh.bussiness.tiku.model.Paper;
import com.xh.bussiness.tiku.service.IPaperService;
import com.xh.bussiness.tms.model.StudentAttend;
import com.xh.bussiness.tms.service.IStudentAttendService;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;

import java.util.ArrayList;
import java.util.List;
/**
 * <p>
 * 课堂练习学生记录表 服务实现类
 * </p>
 *
 * @author Pitt Cheung
 * @since 2021-08-26
 */
@Service
public class StudentExerciseServiceImpl extends BaseServiceImpl<StudentExerciseMapper, StudentExercise> implements IStudentExerciseService {

    @Autowired
    private IExerciseStudentQuestionService studentQuestionService;


    @Autowired
    private IStudentAttendService studentAttendService;

    @Autowired
    private IExerciseService exerciseService;

    @Autowired
    private IPaperService paperService;

    @Override
    public XhPage queryStudentExercisePage(XhPage page, StudentExerciseRequest bean) {
        QueryWrapper qw=new QueryWrapper<StudentExercise>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public List queryStudentExercise(StudentExerciseRequest bean) {
        QueryWrapper qw=new QueryWrapper<StudentExercise>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }


    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(StudentExerciseRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        return qw;
    }

    /**
     * 点击开始评分按钮，自动生成当前课次的学生信息
     * @author 赵文博
     * @date 2021/9/1 10:22
     * @param bean
     * @return boolean
     **/
    @Override
    public boolean addStudentExercise(StudentExerciseRequest bean) {
        //查询出勤学生
        QueryWrapper<StudentAttend> studentAttendQW = new QueryWrapper<>();
        studentAttendQW.eq("class_id",bean.getClassId());
        studentAttendQW.eq("curr_id",bean.getCurrId());
        studentAttendQW.and(wrapper->wrapper.eq("status",1)
                            .or()
                            .eq("status",2));
        List<StudentAttend> studentAttends = studentAttendService.selectList(studentAttendQW,StudentAttend.class);
        //生成出勤学生的评分数据
        List<StudentExercise> exercises = new ArrayList<>();
        for(StudentAttend studentAttend : studentAttends){
            StudentExercise studentExercise = new StudentExercise();
            studentExercise.setStudentId(studentAttend.getStudentId());
            studentExercise.setStudentName(studentAttend.getStudentName());
            studentExercise.setClassId(studentAttend.getClassId());
            studentExercise.setClassName(bean.getClassName());
            studentExercise.setCurrId(studentAttend.getCurrId());
            studentExercise.setCurrName(bean.getCurrName());
            studentExercise.setCurrTime(bean.getCurrTime());
            studentExercise.setCurrDate(bean.getCurrDate());
            exercises.add(studentExercise);
        }
        boolean flag = this.batchInsert(exercises);
        return flag;
    }

    /**
     * 根据班级课次查询学生评价列表
     * @author 赵文博
     * @date 2021/9/1 10:59
     * @param bean
     * @return com.xh.bussiness.exam.model.StudentExercise
     **/
    @Override
    public ExerciseDto queryStudentExerciseList(StudentExerciseRequest bean) {
        ExerciseDto result = new ExerciseDto();

        //获取课堂练习基本信息
        QueryWrapper<Exercise> exerciseQW = new QueryWrapper();
        exerciseQW.eq("class_id",bean.getClassId());
        exerciseQW.eq("curr_id",bean.getCurrId());
        Exercise exercise = exerciseService.selectFirst(exerciseQW);
        if(exercise==null){
            throw new XhException("未查询到该课堂练习");
        }
        //获取试卷类型source_from
        result.setBeforePaperType(getPaperSourceFrom(exercise.getBeforePaperId()));
        result.setBetweenPaperType(getPaperSourceFrom(exercise.getBetweenPaperId()));
        result.setAfterPaperType(getPaperSourceFrom(exercise.getAfterPaperId()));

        //获取出勤率
        ExerciseRequest exerciseRequest = new ExerciseRequest();
        exerciseRequest.setClassId(bean.getClassId());
        exerciseRequest.setCurrId(bean.getCurrId());
        String rate = exerciseService.selectAttendanceRate(exerciseRequest);

        //获取试卷总分
        result.setBeforePaperTotal(getPaperTotal(exercise.getBeforePaperId()));
        result.setBetweenPaperTotal(getPaperTotal(exercise.getBetweenPaperId()));
        result.setAfterPaperTotal(getPaperTotal(exercise.getAfterPaperId()));
        //获取学生课堂练习评分记录
        List<StudentExerciseDto> studentExerciseDtoList = queryStudentExercises(bean);

        //计算试卷均分
        getAvg(studentExerciseDtoList,result);

        result.setClassId(exercise.getClassId());
        result.setClassName(exercise.getClassName());
        result.setCurrId(exercise.getCurrId());
        result.setCurrName(exercise.getCurrName());
        result.setCurrDate(exercise.getCurrDate());
        result.setCurrTime(exercise.getCurrTime());

        result.setBeforePaperId(exercise.getBeforePaperId());
        result.setBetweenPaperId(exercise.getBetweenPaperId());
        result.setAfterPaperId(exercise.getAfterPaperId());

        result.setAttendRate(rate);
        result.setExercises(studentExerciseDtoList);

        return result;
    }

    /**
     * 给试卷评分
     * @author 赵文博
     * @date 2021/9/1 15:40
     * @param bean
     * @return boolean
     **/
    @Override
    public boolean marking(StudentExerciseRequest bean) {
        StudentExercise studentExercise = new StudentExercise();

        //设置试卷分数
        if(bean.getId()==null){
              throw new XhException("id不能为空");
        }
        studentExercise.setId(bean.getId());
        switch (bean.getExerciseType()){
            case 1:studentExercise.setBeforeScore(bean.getScore());studentExercise.setStatus(1);break;
            case 2:studentExercise.setBetweenScore(bean.getScore());studentExercise.setStatus(1);break;
            case 3:studentExercise.setAfterScore(bean.getScore());studentExercise.setStatus(1);break;
        }

        boolean flag = this.dao.updateStudentExercise(studentExercise)>0;

        //添加试题
        if(flag && bean.getQuestions()!=null){
            //删除旧数据
            QueryWrapper<ExerciseStudentQuestion> deleteQW = new QueryWrapper();
            deleteQW.eq("class_id",bean.getClassId());
            deleteQW.eq("curr_id",bean.getCurrId());
            deleteQW.eq("student_id",bean.getStudentId());
            studentQuestionService.deleteByCondition(deleteQW);

            //增加新数据
            List<ExerciseStudentQuestion> questions = new ArrayList<>();
            for(ExerciseStudentQuestion question:bean.getQuestions()){
                question.setClassId(bean.getClassId());
                question.setCurrId(bean.getCurrId());
                question.setStudentId(bean.getStudentId());
                questions.add(question);
            }
            flag = studentQuestionService.batchInsert(questions);
        }
        return flag;
    }

    /**
     * 给学生评论
     * @author 赵文博
     * @date 2021/9/1 15:47
     * @param studentExercise
     * @return boolean
     **/
    @Override
    public boolean updateComment(StudentExercise studentExercise) {
        if(studentExercise.getId()==null){
            throw new XhException("id不能为空");
        }
        boolean flag = this.dao.updateStudentExercise(studentExercise)>0;
        return flag;
    }

    /**
     * 获取试卷总分
     * @author 赵文博
     * @date 2021/9/1 11:38
     * @param paperId
     * @return java.lang.Integer
     **/
    private Integer getPaperTotal(String paperId){
        if(paperId==null){
            return null;
        }
        QueryWrapper<Paper> paperQW = new QueryWrapper<>();
        paperQW.eq("id",paperId);
        Paper paper = paperService.selectFirst(paperQW);
        if(paper==null){
            return null;
        }
        return paper.getTotalScore();
    }

    private void getAvg(List<StudentExerciseDto> studentExerciseList, ExerciseDto result){
        double before = 0.0;
        Integer beforeCount = 0;
        double between = 0.0;
        Integer betweenCount = 0;
        double after = 0.0;
        Integer afterCount = 0;
        for(StudentExerciseDto studentExercise:studentExerciseList){
            if(studentExercise.getBeforeScore() != null){
                before += Double.valueOf(studentExercise.getBeforeScore());
                beforeCount++;
            }

            if(studentExercise.getBetweenScore() != null){
                between += Double.valueOf(studentExercise.getBetweenScore());
                betweenCount++;
            }

            if(studentExercise.getAfterScore() != null){
                after += Double.valueOf(studentExercise.getAfterScore());
                afterCount++;
            }
        }
        if(beforeCount>0){
            double value = (before/beforeCount);
            result.setBeforePaperAvg(String.format("%.1f", value));
        }
        if(betweenCount>0){
            double value = (between/beforeCount);
            result.setBetweenPaperAvg(String.format("%.1f", value));
        }
        if(afterCount>0){
            double value = (after/afterCount);
            result.setAfterPaperAvg(String.format("%.1f", value));
        }
    }

    private Integer getPaperSourceFrom(String paperId){
        if(paperId!=null){
            Paper paper = paperService.getById(paperId);
            if(paper!=null){
                return paper.getSourceFrom();
            }
        }
        return 4;
    }

    @Override
    public List<StudentExercise> selectTeacherIdByStudentId(String studentId) {

        return this.dao.selectTeacherIdByStudentId(studentId);
    }

    @Override
    public List<StudentExerciseDto> queryStudentExercises(StudentExerciseRequest bean) {
        return this.dao.queryStudentExercises(bean);
    }
}
